from . import funcSearch
from flask import Flask,render_template,request,url_for,redirect,session
from apps.spider import searchEngineSpider, biquSpider
from da import Ua
import json

@funcSearch.route('/index/<path:chapter_url>/<int:index>')
def index(chapter_url, index):
    novelCatalogue = session.get("novelCatalogue")

    data = {"index": index, "prevChapter_url": novelCatalogue[index-1].get("chapter_url") if index > 0 else index, "nextChapter_url": novelCatalogue[index+1].get("chapter_url") if index < len(novelCatalogue)-1 else index} #文章翻页
    detail = biquSpider.parseContent(chapter_url)
    return render_template("index.html",item=detail,data=data)

@funcSearch.route("/parseSearch", methods=["POST"])
def parseSearch():
    bookName = request.form.get("search")
    return redirect(url_for("funcSearch.searchList",bookName=bookName))

@funcSearch.route("/searchlist/?<string:bookName>")
def searchList(bookName):
    baidu_list = searchEngineSpider.parseBaidu(bookName)
    return render_template("searchlist.html",baidu_list=baidu_list)



@funcSearch.route("/toCatalogue/<path:baidu_url>/<baidu_title>")
def toCatalogue(baidu_url,baidu_title):
    # print(baidu_url,baidu_title.encode('utf-8').decode('utf-8'))
    session['username'] = 'liefyuan'
    # print(session)
    novelCatalogue = biquSpider.getNovelHtml(baidu_url, {"User-Agent": Ua.randomUA()})
    session["novelCatalogue"] = novelCatalogue
    return render_template("catalogue.html",novelCatalogue=novelCatalogue)


@funcSearch.route("/test")
def test():
    return render_template("test.html")
